package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.mapper.IntegralGradeMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.IntegralGrade;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.service.IntegralGradeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 积分等级表 服务实现类
 * </p>
 *
 * @author Mr.bilal
 * @since 2023-07-18
 */
@Service
public class IntegralGradeServiceImpl extends ServiceImpl<IntegralGradeMapper, IntegralGrade> implements IntegralGradeService {

    @Resource
    UserInfoMapper userInfoMapper;

    @Override
    public BigDecimal getBorrowAmount(String userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Integer integral = userInfo.getIntegral();
        QueryWrapper<IntegralGrade> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .le("integral_start",integral)
                .ge("integral_end",integral);
        List<IntegralGrade> integralGrades = baseMapper.selectList(queryWrapper);

        if (integralGrades.size() > 1){
            return integralGrades.stream()
                    .map(IntegralGrade::getBorrowAmount)
                    .max(BigDecimal::compareTo)
                    .orElse(BigDecimal.ZERO);
        }
        if (!integralGrades.isEmpty()) {
            return integralGrades.get(0).getBorrowAmount();
        }
        return new BigDecimal("0");
    }
}
